package com.jet.multichat.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Collection;

public class ChatMessageService {
	private String content;

	public ChatMessageService(Socket socket) throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		this.content = reader.readLine();
	}

	public ChatMessageService(Socket socket, String prefix) throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		this.content = prefix + reader.readLine();
	}

	public ChatMessageService(BufferedReader reader) throws IOException {
		this.content = reader.readLine();
	}

	public ChatMessageService(String string) throws IOException {
		this.content = string;
	}
	
	public ChatMessageService(ChatThread chatThread) throws IOException {	
		BufferedReader reader = new BufferedReader(new InputStreamReader(chatThread.getSocket().getInputStream()));
		this.content = chatThread.getLogin() + " > " + reader.readLine();
	}
	
	public String getContent() {
		return content;
	}

	public void send(Socket socket) throws IOException {
		PrintWriter writer = new PrintWriter(socket.getOutputStream());
		writer.println(content);
		writer.flush();
	}

	public void sendToGroup(Collection<ChatThread> group) throws IOException {
		for (ChatThread chatThread : group) {
			send(chatThread.getSocket());
		}
	}
	
	public void show() {
		System.out.println(content);
	}
}
